package com.qf.shopsearch.controller;

import com.qf.entity.Goods;
import org.apache.commons.beanutils.BeanUtils;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.text.Text;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;

import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/search")
public class SearchController {
    @Autowired
    private RestHighLevelClient client;
    @Value("${elasticsearch.index}")
    private String index;
    @Value("${elasticsearch.type}")
    private String type;

    @RequestMapping("/goods")
    public String add(String keyword, ModelMap modelMap) throws IOException, InvocationTargetException, IllegalAccessException {
        SearchRequest request = new SearchRequest(index);
        request.types(type);
        SearchSourceBuilder builder = SearchSourceBuilder.searchSource();

        //高亮显示
        HighlightBuilder highlighter = new HighlightBuilder();
        //要显示的高亮字段名，以及显示的字数
        highlighter.field("gname", 30);
        highlighter.preTags("<font color='red'>");
        highlighter.postTags("</font>");
        builder.highlighter(highlighter);

        //判断传来的keyword是否为空
        if (StringUtils.isEmpty(keyword)) {
            //空表示没有关键字，就查询所有
            builder.query(QueryBuilders.matchAllQuery());
        } else {
            //多种查询条件
            builder.query(QueryBuilders.multiMatchQuery(keyword, "gname", "gdesc"));
        }
        request.source(builder);
        //用list来装从es中查询的数据
        List<Goods> list = new ArrayList();
        SearchResponse search = client.search(request, RequestOptions.DEFAULT);
        SearchHit[] hits = search.getHits().getHits();
        for (int i = 0; i < hits.length; i++) {
            Map<String, Object> sourceAsMap = hits[i].getSourceAsMap();
            Goods goods = new Goods();
            //map中的信息拷贝到goods中
            BeanUtils.populate(goods, sourceAsMap);
            //判断结果集中是否存在高亮字段
            Map<String, HighlightField> highlightFields = hits[i].getHighlightFields();
            if (!highlightFields.isEmpty()) {
                //不为空，说明有高亮
                HighlightField gname = highlightFields.get("gname");
                Text[] fragments = gname.fragments();
                //用高亮信息覆盖掉gname的信息
                goods.setGname(fragments[0].toString());
            }
            list.add(goods);
        }
        modelMap.put("searchList", list);
        System.out.println("搜索的list:" + list);
        return "searchList";
    }
}
